<template>
  <div class="login-form">
    <el-form ref="form" :model="form" label-width="80px" :rules="accrule">
      <el-form-item label="商家账号" prop="username">
        <el-input v-model="form.username" placeholder="请输入商家账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入商家密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" @click="submitForm('form')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'LoginByUserAccount',
  data () {
    // 自定义校验规则
    var checkUserAccount = (rule, username, callback) => {
      if (!username) {
        return callback(new Error('商家账号不能为空'))
      }
      setTimeout(() => {
        if (!(/^[a-zA-Z0-9_-]{6,12}$/).test(username)) {
          callback(new Error('请输入6-12位的用户名'))
        } else {
          // 向数据库查询用户名是否存在
          // this.$http.get('', {
          //   username: this.form.username
          // }).then(({data}) => {
          //   if (data === '1') {
          //     alert('账号登录')
          //   } else {
          callback()
          // }
          // })
        }
      }, 500)
    }
    var validatePass = (rule, password, callback) => {
      if (!password) {
        return callback(new Error('你还没有输入你的密码呢'))
      }
      setTimeout(() => {
        if (!(/^[a-zA-Z0-9_-]{6,12}$/).test(password)) {
          callback(new Error('密码长度为6-12位'))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      form: {
        username: '',
        password: ''
      },
      accrule: {
        username: [
          { validator: checkUserAccount, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
  .login-form
    width: 350px
    box-sizing border-box
    .el-button
      margin-left: -20px
    .login-btn
      margin-top 20px
      width: 100%
</style>
